﻿using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging;
using PmSoft.Web.Abstractions.RealTime;

namespace PmSoft.Web.Abstractions.SignalR.Hubs;

public abstract class OnlineClientHubBase : Hub
{
	private readonly ILogger logger;
	public OnlineClientHubBase(ILogger logger,
		IOnlineClientManager onlineClientManager, 
		IOnlineClientInfoProvider onlineClientInfoProvider)
	{
		this.logger = logger;
		OnlineClientManager = onlineClientManager;
		OnlineClientInfoProvider = onlineClientInfoProvider;
	}

	protected IOnlineClientManager OnlineClientManager { get; }

	protected IOnlineClientInfoProvider OnlineClientInfoProvider { get; }

	public override async Task OnConnectedAsync()
	{
		await base.OnConnectedAsync();

		var client = CreateClientForCurrentConnection();

		logger.LogDebug("A client is connected: " + client);

		await OnlineClientManager.AddAsync(client);
	}

	public override async Task OnDisconnectedAsync(Exception? exception)
	{
		await base.OnDisconnectedAsync(exception);

		logger.LogDebug("A client is disconnected: " + Context.ConnectionId);

		try
		{
			await OnlineClientManager.RemoveAsync(Context.ConnectionId);
		}
		catch (Exception ex)
		{
			logger.LogWarning(ex.ToString(), ex);
		}
	}

	protected virtual IOnlineClient CreateClientForCurrentConnection()
	{
		return OnlineClientInfoProvider.CreateClientForCurrentConnection(Context);
	}
}
